package com.guobo.gateways.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@过滤器");
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        if ("/user/login".equals(path)) {
            System.out.println("放行--------------------");
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (token == null || "undefined".equals(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            System.out.println("未登录,跳到登录页--------------------");
            return exchange.getResponse().setComplete();
        }
        System.out.println("放行--------------------");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
